public class HashBuck {

    class Node {
        int key;
        int val;
        Node random;
        Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
        public Node(int val) {
            this.val = val;
        }
    }

    public  int usedSize;
    public Node[] array;
    public static final double LOAD_FACTOR = 0.75;

    public HashBuck() {
        this.array = new Node[10];
    }

    public void put(int key,int val) {
        int index = key % array.length;
        Node cur = array[index];
        //寻找数据中是否有相同的数据，如果有将val的值进行更新
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
            }
            cur = cur.next;
        }
        //头插法放入数据，array[index]存储的是头结点的地址
        Node node = new Node(key, val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //判断是否超过了负载因子，超过了需要进行扩容
        if (calculateLoadFactor() >= LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                int index = cur.key % array.length;
                Node curNext = cur.next;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }

    private double calculateLoadFactor() {
        return usedSize*1.0 / array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

}
